
// 等待态
const Pending = 'pending'
// 成功态
const Fulfilled = 'fulfilled'
// 失败态
const Rejected = 'rejected'

class MyPromise {
    constructor(executor) {
        // 同步执行
        executor(this._resolve, this._reject)
    }

    // Promise 状态
    _status = Pending

    // 成功回调数组
    _success = []

    // 失败回调数组
    _fail = []

    // 内容 resolve 方法 , 注意剪头函数，实际调用的时候， this 指向
    _resolve = (value) => {
        // 只有处于等待态 的 Promise 才会有 状态跃迁
        if (Object.is(this._status, Pending)) {
            setTimeout(() => {
                // 设置状态
                this._status = Fulfilled;
                // 执行回调
                while (this._success.length) {
                    // then 方法的 onFulfilled
                    const successCallback = this._success.shift();
                    successCallback(value)
                }
            }, 0);
        }
    }

    // 内部 reject 方法
    _reject = (error) => {
        // 只有处于等待态 的 Promise 才会有 状态跃迁
        if (Object.is(this._status, Pending)) {
            // 设置状态
            this._status = Rejected;
        }
    }

    // onFulfilled: any => Promise<any>
    then(onFulfilled, onRejected) {

        // 兜底调用
        onFulfilled = onFulfilled ? onFulfilled : value => value;
        onRejected = onRejected ? onRejected : error => error;

        // 保存 回调函数
        this._success.push(onFulfilled)
        this._fail.push(onRejected)
    }

    catch(onFulfilled) {

    }

    finally(onFinished) {

    }

    static resolve(value) {
        return new MyPromise((resolve) => {
            resolve(value)
        })
    }

    static reject(error) {
        return new MyPromise((undefined, reject) => {
            reject(error)
        })
    }

    static all() {}

    static race() {}
}

module.exports = MyPromise